<template>



  <!--- 观看历史 待添加   --->

  <div class="tab" v-for="tabItem in tabs" :key="tabItem.id">


    <van-loading v-if="loading" class="loading" />

    <div class="tab-title">
      {{ tabItem.name }}
    </div>
    <Content :tabItem="tabItem" />
    <div class="tab-buttons">
      <van-button block round size="small" color="#efefef" @click="exchange(tabItem)">换一换</van-button>
      <van-button block round size="small" color="#efefef" @click="gotoMore(tabItem)">查看更多</van-button>
    </div>
  </div>
</template>
<script setup>
import { getHomeExchange } from "@/api/index.js"

import { ref, onMounted, watch } from 'vue'

const loading = ref(false)

const props = defineProps(['tab'])

const tabs = ref([]);


// 初始化 tabs 数据
onMounted(() => {
  if (props.tab && props.tab.length > 0) {
    tabs.value = [...props.tab]; // 深拷贝以避免直接修改 props
  }
})

// 监听 props.tab 的变化，确保 tabs 始终与 props.tab 同步
watch(
  () => props.tab,
  (newTab) => {
    // console.log(" watch newTab", newTab);
    tabs.value = [...newTab]; // 更新 tabs 数据
  },
  { immediate: true } // 立即执行一次，确保初始化时同步
)




import { useRouter } from 'vue-router'
const router = useRouter()

import { useStore } from "@/stores/index.js"
const store = useStore()


function replaceObjectInTab (tabs, exchangeTabItem) {
  const targetId = String(exchangeTabItem.id); // 确保类型一致
  return tabs.map(item => String(item.id) === targetId ? exchangeTabItem : item);
}


//换一换
const exchange = async (tabItem) => {
  try {

    loading.value = true; // 显示 loading

    const res = await getHomeExchange(tabItem.id); // 调用 API 获取新数据
    const newTabItem = res.data; // 新的数据对象

    // console.log("0 tabs.value ", tabs.value);
    // console.log("newTabItem", newTabItem);

    // tabs.value = replaceObjectInTab(tabs.value, newTabItem); // 替换对应 tab 数据
    tabs.value = [...replaceObjectInTab(tabs.value, newTabItem)];
    // console.log("1 tabs.value", tabs.value);


    loading.value = false; // 隐藏 loading

  } catch (error) {
    console.error('换一换失败:', error);
  }

}


// tab列表
const gotoMore = (tabItem) => {
  // console.log("tabItem", tabItem.id);
  store.setTabListName(tabItem.name)
  router.push({ path: `/tabList/${tabItem.id}` })
};






</script>
<style scoped>
.tab {
  position: relative;
  margin-bottom: 10px;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
}



.tab-title {
  padding: 20px 10px 0 10px;
}

.tab-buttons {
  margin-top: 10px;
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(2, 1fr);
  color: #333;
  padding: 0 10px;
}

:deep(.van-button__text) {
  color: #666;
}
</style>
